package com.cn.learn.jpa.controller;

import com.cn.learn.jpa.util.DownloadUtil;
import com.cn.learn.jpa.util.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @ClassName FileController
 * @Description
 * @Author JiJiang
 * @Date 2022/9/15 14:37
 * @Version 1.0
 */

@RestController
@RequestMapping("/file")
public class FileController {

    //文件保存的根路径
    private static final String DIR_ROOT = "J:\\Tomcat\\9.0\\apache-tomcat-9.0.62\\webapps";

    //文件保存的位置
    private static final String DIR_UPLOAD = "\\WanXiWeb\\upload";

    //访问的资源地址与端口
    private static final String HOST = "http://127.0.0.1:8080";


    /**
     * @MethodName uploadFile
     * @Description 上传单个文件
     * @Param [multipartFile]
     * @Return java.lang.String
     **/
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        if (multipartFile == null) {
            return "上传文件为null";
        }
        String originName = multipartFile.getOriginalFilename();


        //2.文件的后缀名 如png，jpg，exe
        String fileSuffixName = originName.substring(originName.lastIndexOf('.') + 1);


        //region 3.得到全文件名 （路径名+文件名）

        StringBuilder stringBuilder = new StringBuilder();

        //文件保存的根目录
        stringBuilder.append(DIR_ROOT);
        //目录分隔符
        stringBuilder.append(File.separator);
        //文件的上传的目录
        stringBuilder.append(DIR_UPLOAD);
        //目录与文件的分隔符
        stringBuilder.append(File.separator);

        //文件名
        stringBuilder.append(System.currentTimeMillis());

        //文件名与后缀名的分割符
        stringBuilder.append(".");
        //文件后缀名
        stringBuilder.append(fileSuffixName);

        //最终的文件名
        String saveFileFullName = stringBuilder.toString();

        //endregion


        //4.使用io的方式将文件进行保存
        multipartFile.transferTo(new File(saveFileFullName));


        //5.获取文件名
        String saveFileName = saveFileFullName.substring(saveFileFullName.lastIndexOf(File.separator) + 1);


        return (HOST + DIR_UPLOAD + "/" + saveFileName);

    }


    @GetMapping("/download")
    public void downloadFile(String downloadFileName, HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取下载文件的路径
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(DIR_ROOT);
        stringBuilder.append(DIR_UPLOAD);
        String fileDir = stringBuilder.toString();

        //创建下载文件的文件对象
        File downloadFile = new File(fileDir, downloadFileName);

        //创建该文件对象的字节输入流  ---> 将该文件以字节形式加载到内存
        FileInputStream fileInputStream = new FileInputStream(downloadFile);

        //获取全局上下文对象
        ServletContext servletContext = request.getServletContext();


        ///region 设置响应头
        //获取需要下载文件的mimetype 即类似text/html
        String mimeType = servletContext.getMimeType(downloadFileName);

        //将文件类型添加至响应头
        response.setHeader("content-type", mimeType);

        ///解决下载文件中文乱码

        //获取代理 -->即浏览器的类型（如IE、FireFox、Google ）
        String agent = request.getHeader("user-agent");

        //根据对应的浏览器代理，解析其对应的名字
        downloadFileName = DownloadUtil.getFileName(agent, downloadFileName);

        //设置文件的打开方式为附属
        response.setHeader("content-disposition",
                "attachment;filename =" + downloadFileName);

        //endregion


        //设置缓冲区为1M
        byte[] buffer = new byte[1024];

        //读取的真实长度
        int len = 0;

        //将字节输入流对象的数据读到字节输出流对象中
        while ((len = fileInputStream.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
        //关闭字节输入流对象
        fileInputStream.close();

    }


    @PostMapping("/uploads")
    public void uploadDir(@RequestParam("file") MultipartFile[] files) throws IOException {


        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append(DIR_ROOT);
        stringBuffer.append(DIR_UPLOAD);
        stringBuffer.append(File.separator);


        String dir = stringBuffer.toString();
        for (MultipartFile file : files) {


//             FileUtil.saveFileFromByteStream(,new File(dir+file));

            FileUtil.saveFileFromByteArr(file.getBytes(), new File(dir + file.getOriginalFilename()));

//             file.transferTo(new File(dir+file));
            stringBuffer.append(file.getOriginalFilename() + "\n");
            System.out.println(file.getOriginalFilename());
            System.out.println(file.getName());

        }


    }


}
